//
//  ReceivedExpressViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/8/27.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "ReceivedExpressViewController.h"
#import "ExpressDetailViewController.h"
#import "DropMenuButton.h"
#import "SocketRequest.h"
#import "Singleton.h"
#import "ReceivedExpressGroup.h"
#import "ReceivedExpressCell.h"
#import "UITableView+Activity.h"

@interface ReceivedExpressViewController ()<DropMenuButtonDelegate,SocketRequestDelegate,ExpressDetailViewControllerDelegate> {
    SocketRequest *_socketRequest;
    int _positionPage;
    NSString *_expressType;
    NSMutableArray *_receivedExpressList;
}

@end

@implementation ReceivedExpressViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"已接收快递";
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
        _positionPage = 1;
        _expressType = @"00";
        _receivedExpressList = [NSMutableArray arrayWithCapacity:1];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSArray *menus = nil;
    if (self.expressSendType == ExpressSendTypeZiti) {
        menus = @[@"全部", @"待自提", @"已逾期", @"已退件", @"客户签收"];
    } else if (self.expressSendType == ExpressSendTypeVisit) {
        menus = @[@"全部", @"待配送", @"已逾期", @"已退件", @"小站代签", @"客户自签"];
    }
    DropMenuButton *menuButton = [[DropMenuButton alloc] initWithMenus:menus InView:self.view];
    menuButton.delegate = self;
    UIBarButtonItem *menuBarButton = [[UIBarButtonItem alloc] initWithCustomView:menuButton];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = -15;
    self.navigationItem.rightBarButtonItems = @[negativeSpacer, menuBarButton];
    [self getExpressListFromeSqlit];
    [self handelNetWorkMethod];
}

- (void)getExpressListFromeSqlit {
    [_receivedExpressList removeAllObjects];
    NSString *sql = [NSString stringWithFormat:@"WHERE sendType = '%ld' AND socketExpressType = '%@' ORDER BY receiveTime DESC",(long)self.expressSendType,_expressType];
    NSArray *array = [ReceivedExpress findByCriteria:sql];
    for (ReceivedExpress *express in array) {
        ReceivedExpressGroup *group = [_receivedExpressList lastObject];
        if ([group.showDay isEqualToString:express.showDay]) {
            [group.expressList addObject:express];
        } else {
            ReceivedExpressGroup *anotherGroup = [[ReceivedExpressGroup alloc] initWithReceivedExpress:express];
            [anotherGroup.expressList addObject:express];
            [_receivedExpressList addObject:anotherGroup];
        }
    }
    self.tableView.isShowFooterView = NO;
    [self.tableView reloadData];
    if (_receivedExpressList.count > 0) {
        [ToastActivity makeActivity:@"正在加载中..." InView:self.view];
    }
    [self getReceivedExpressSocket];
}

//获取已接收socket
- (void)getReceivedExpressSocket {
    if (_receivedExpressList.count <= 0) {
        [self.tableView makeLoading];
    } else {
        [self.tableView makeNone];
    }
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STR3"]];
    if (self.expressSendType == ExpressSendTypeZiti) {
        [mutableData appendBytes:[@"00" UTF8String] length:2];
    } else if (self.expressSendType == ExpressSendTypeVisit) {
        [mutableData appendBytes:[@"01" UTF8String] length:2];
    }
    [mutableData appendBytes:[SocketMethod checkLegal:_expressType] length:2];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    NSString *positionString = [NSString stringWithFormat:@"%d",_positionPage];
    [mutableData appendBytes:[SocketMethod checkLegal:positionString] length:16];
    [mutableData appendBytes:[@"10" UTF8String] length:16];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

- (void)reloadTableViewWithLoaded:(BOOL)isLoaded {
    self.tableView.isShowFooterView = !isLoaded;
    if (_receivedExpressList.count <= 0) {
        [self.tableView makeTip:[self tipExpressType]];
    } else {
        [self.tableView makeNone];
    }
    [self.tableView reloadData];
}

- (NSString *)tipExpressType {
    if ([_expressType isEqualToString:@"00"]) {
        return @"无已接收快递";
    } else if ([_expressType isEqualToString:@"01"]) {
        return @"无待自提快递";
    } else if ([_expressType isEqualToString:@"02"]) {
        return @"无待配送快递";
    } else if ([_expressType isEqualToString:@"03"]) {
        return @"无已逾期快递";
    } else if ([_expressType isEqualToString:@"04"]) {
        return @"无已退件快递";
    } else if ([_expressType isEqualToString:@"05"]) {
        return @"无客户签收快递";
    } else if ([_expressType isEqualToString:@"06"]) {
        return @"无小站代签快递";
    } else if ([_expressType isEqualToString:@"07"]) {
        return @"无客户自签快递";
    } else {
        return @"";
    }
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _receivedExpressList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    ReceivedExpressGroup *group = [_receivedExpressList objectAtIndex:section];
    return group.expressList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 22;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 22)];
    headerView.backgroundColor = UIColorFromRGB(0xebebeb);
    ReceivedExpressGroup *group = [_receivedExpressList objectAtIndex:section];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(12, 1, 150, 20)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:11];
    label.textColor = TipTextColor;
    label.text = [NSString stringWithFormat:@"%@(%d)",group.showDay,group.dayCount];
    [headerView addSubview:label];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 64;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIndentifier = @"ReceivedExpressCell";
    ReceivedExpressCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ReceivedExpressCell" owner:self options:nil] lastObject];
    }
    ReceivedExpressGroup *group = [_receivedExpressList objectAtIndex:indexPath.section];
    ReceivedExpress *express = [group.expressList objectAtIndex:indexPath.row];
    [cell reloadReceivedExpressCellWithReceivedExpress:express];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ReceivedExpressGroup *group = [_receivedExpressList objectAtIndex:indexPath.section];
    ReceivedExpress *express = [group.expressList objectAtIndex:indexPath.row];
    ExpressDetailViewController *expressDVC = [[ExpressDetailViewController alloc] initWithNibName:@"ExpressDetailViewController" bundle:nil];
    expressDVC.inwayExpressId = express.inwayExpressId;
    expressDVC.delegate = self;
    expressDVC.indexPath = indexPath;
    [self.navigationController pushViewController:expressDVC animated:YES];
}

#pragma mark ExpressDetailViewControllerDelegate
- (void)smsSendSuccess:(NSIndexPath *)indexPath {
    ReceivedExpressGroup *group = [_receivedExpressList objectAtIndex:indexPath.section];
    ReceivedExpress *express = [group.expressList objectAtIndex:indexPath.row];
    express.smsSendType = 0;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)takeExpressSuccess:(NSIndexPath *)indexPath {
    ReceivedExpressGroup *group = [_receivedExpressList objectAtIndex:indexPath.section];
    ReceivedExpress *express = [group.expressList objectAtIndex:indexPath.row];
    express.expressType = @"0033";
    [express deleteObject];
    [group.expressList removeObject:express];
    group.dayCount --;
    if (group.dayCount == 0) {
        [_receivedExpressList removeObject:group];
        [self.tableView reloadData];
    } else {
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (void)updateExpress:(NSIndexPath *)indexPath Telephone:(NSString *)telephone Address:(NSString *)address Position:(NSString *)position {
    ReceivedExpressGroup *group = [_receivedExpressList objectAtIndex:indexPath.section];
    ReceivedExpress *express = [group.expressList objectAtIndex:indexPath.row];
    express.expressType = @"0006";
    express.smsSendType = 0;
    [express saveOrUpdate];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.tableView pullScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self.tableView pullscrollViewDidEndDragging:scrollView];
}

#pragma mark PullTableViewDelegate
- (void)startRefreshHeaderView {
    _positionPage = 1;
    [self getReceivedExpressSocket];
}

- (void)startRefreshFooterView {
    _positionPage += 10;
    [self getReceivedExpressSocket];
}

#pragma mark DropMenuButtonDelegate
- (void)clickedButtonWithSearchType:(NSString *)searchType {
    self.tableView.contentOffset = CGPointMake(0, 0);
    if (self.expressSendType == ExpressSendTypeZiti) {
        if ([searchType isEqualToString:@"00"]) {
            [MobClick event:@"zitijian_link_quanbu"];
        } else if ([searchType isEqualToString:@"01"]) {
            [MobClick event:@"zitijian_link_daiziti"];
        } else if ([searchType isEqualToString:@"03"]) {
            [MobClick event:@"zitijian_link_yiyuqi"];
        } else if ([searchType isEqualToString:@"04"]) {
            [MobClick event:@"zitijian_link_yituijian"];
        } else if ([searchType isEqualToString:@"05"]) {
            [MobClick event:@"zitijian_link_kehuqianshou"];
        }
    } else if (self.expressSendType == ExpressSendTypeVisit) {
        if ([searchType isEqualToString:@"00"]) {
            [MobClick event:@"shangmenjian_link_quanbu"];
        } else if ([searchType isEqualToString:@"02"]) {
            [MobClick event:@"shangmenjian_link_daipeisong"];
        } else if ([searchType isEqualToString:@"03"]) {
            [MobClick event:@"shangmenjian_link_yiyuqi"];
        } else if ([searchType isEqualToString:@"04"]) {
            [MobClick event:@"shangmenjian_link_yituijian"];
        } else if ([searchType isEqualToString:@"06"]) {
            [MobClick event:@"shangmenjian_link_xiaozhandaiqian"];
        } else if ([searchType isEqualToString:@"07"]) {
            [MobClick event:@"shangmenjian_link_kehuziqian"];
        }
    }
    _expressType = searchType;
    _positionPage = 1;
    [self getExpressListFromeSqlit];
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    [self.tableView endRefreshPullTableView];
    [ToastActivity dismissInView:self.view];
    if ([code isEqualToString:SuccessSocket]) {
        if (_positionPage == 1) {
            [_receivedExpressList removeAllObjects];
            NSString *sql = [NSString stringWithFormat:@"WHERE sendType = '%ld' AND socketExpressType = '%@'",(long)self.expressSendType,_expressType];
            [ReceivedExpress deleteObjectsByCriteria:sql];
        }
        NSString *content = [SocketMethod stringDecryHexData:data];
        int i = 0;
        NSArray *array = [content componentsSeparatedByString:@"|"];
        for (NSString *string in array) {
            if (string.length > 0) {
                ReceivedExpress *recievedExpress = [[ReceivedExpress alloc] initWithString:string];
                recievedExpress.sendType = self.expressSendType;
                recievedExpress.socketExpressType = _expressType;
                [recievedExpress saveOrUpdate];
                ReceivedExpressGroup *group = [_receivedExpressList lastObject];
                if ([group.showDay isEqualToString:recievedExpress.showDay]) {
                    [group.expressList addObject:recievedExpress];
                } else {
                    ReceivedExpressGroup *anotherGroup = [[ReceivedExpressGroup alloc] initWithReceivedExpress:recievedExpress];
                    [anotherGroup.expressList addObject:recievedExpress];
                    [_receivedExpressList addObject:anotherGroup];
                }
                i ++;
            }
        }
        [self reloadTableViewWithLoaded:((i < 10) ? YES : NO)];
        DLog(@"%@",content);
    } else {
        if (_receivedExpressList.count <= 0) {
            [self.tableView makeTip:msg];
        } else {
            [DSToast showText:msg InView:self.view];
        }
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    [self.tableView endRefreshPullTableView];
    self.tableView.isShowFooterView = NO;
    [ToastActivity dismissInView:self.view];
    if (_receivedExpressList.count <= 0) {
        [self.tableView makeTip:msg Title:@"重新加载" Target:self Selector:@selector(getReceivedExpressSocket)];
    }
    [DSToast showText:msg InView:self.view];
}

- (void)dealloc {
    _socketRequest = nil;
    _receivedExpressList = nil;
}

@end
